package com.pangda.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pangda.common.constant.BusinessStatusConstant;
import com.pangda.common.domain.PageResult;
import com.pangda.common.domain.ResponseResult;
import com.pangda.common.utils.UserContext;
import com.pangda.pojo.Business;
import com.pangda.pojo.Records;
import com.pangda.pojo.dto.AssignmentDto;
import com.pangda.pojo.dto.BusinessDto;
import com.pangda.pojo.dto.RecordsDto;
import com.pangda.pojo.vo.BusinessVo;
import com.pangda.pojo.vo.RecordsVo;
import com.pangda.service.IBusinessService;
import com.pangda.service.IRecordsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商机管理 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-21
 */
@RestController
@RequestMapping("/business")
@Api(tags = "商机管理")
public class BusinessController {
    @Autowired
    private IBusinessService businessService;

    @Autowired
    private IRecordsService recordsService;

    @GetMapping("/list")
    public PageResult<BusinessVo> list(@ApiParam("分页参数") Integer pageNum,
                                       @ApiParam("分页参数") Integer pageSize,
                                       BusinessDto businessDto) {
        Object beginCreateTime = businessDto.getParams().get("beginCreateTime");
        Object endCreateTime = businessDto.getParams().get("endCreateTime");
        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(businessDto.getName()), Business::getName, businessDto.getName());
        wrapper.like(ObjectUtil.isNotEmpty(businessDto.getOwner()), Business::getOwner, businessDto.getOwner());
        wrapper.between(ObjectUtil.isNotEmpty(beginCreateTime) && ObjectUtil.isNotEmpty(endCreateTime), Business::getCreateTime, beginCreateTime, endCreateTime+" 23:59:59");

        wrapper.like(ObjectUtil.isNotEmpty(businessDto.getPhone()), Business::getPhone, businessDto.getPhone());
        wrapper.like(ObjectUtil.isNotEmpty(businessDto.getId()), Business::getId, businessDto.getId());
        wrapper.eq(ObjectUtil.isNotEmpty(businessDto.getStatus()), Business::getStatus, businessDto.getStatus());
        wrapper.ne(Business::getStatus, BusinessStatusConstant.CLIENT);
        wrapper.ne(Business::getStatus, BusinessStatusConstant.OPEN_OCEAN_POOLS);
        wrapper.ne(Business::getStatus, BusinessStatusConstant.TRANSFORM_TO_BUSINESS);


        Page<Business> page = businessService.page(new Page<>(pageNum, pageSize), wrapper);
        return PageResult.success(page, BusinessVo.class);

    }

    @PostMapping
    public ResponseResult add(@RequestBody BusinessDto businessDto) {
        businessDto.setOwner(UserContext.getUser());
        businessDto.setOwnerTime(LocalDateTime.now());
        businessDto.setCreateBy(UserContext.getUser());
        Business business = new Business();
        business.setCreateBy(UserContext.getUser());
        business.setCreateTime(LocalDateTime.now());
        business.setStatus(businessDto.getStatus());
        business.setCourseId(businessDto.getCourseId());
        business.setClueId(businessDto.getClueId());
        BeanUtil.copyProperties(businessDto, business);
        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Business::getId, business.getId());
        businessService.save(business);
        return ResponseResult.success();

    }

    @GetMapping("/{id}")
    public ResponseResult get(@PathVariable("id") Integer id) {
        return ResponseResult.success(businessService.getById(id));
    }

    @PutMapping
    public ResponseResult update(@RequestBody BusinessDto businessDto) {
        Business business = new Business();
        BeanUtil.copyProperties(businessDto, business);
        businessService.updateById(business);
        return ResponseResult.success();
    }

    @PostMapping("/record")
    public ResponseResult recordAdd(@RequestBody BusinessDto businessDto) {

        Records records = new Records();
        BeanUtil.copyProperties(businessDto, records);
        records.setCreateTime(LocalDateTime.now());
        records.setCreateBy(UserContext.getUser());
        records.setKeyItems(JSONUtil.toJsonStr(businessDto.getKeyItems()));
        records.setKeyItemsArray(JSONUtil.toJsonStr(businessDto.getKeyItemsArray()));
        records.setBusinessId(Integer.valueOf(businessDto.getBusinessId()));
        recordsService.save(records);



        Business business = new Business();
        BeanUtils.copyProperties(businessDto, business);

        business.setId(Long.valueOf(businessDto.getBusinessId()));


        business.setPlanTime(businessDto.getPlanTime());
        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Business::getId, businessDto.getBusinessId());
        businessService.update(business, wrapper);

        return ResponseResult.success();
    }

    @GetMapping("/record/list")
    public ResponseResult recordList(Integer businessId) {
        LambdaQueryWrapper<Records> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotEmpty(businessId), Records::getBusinessId, businessId);
        List<Records> list = recordsService.list(wrapper);
        List<RecordsVo> collect = list.stream().map(item -> {
            RecordsVo bean = BeanUtil.toBean(item, RecordsVo.class);
            bean.setKeys(JSONUtil.toList(item.getKeyItemsArray(), String.class));
            return bean;
        }).collect(Collectors.toList());
        return ResponseResult.success(collect);
    }

    @GetMapping("/record/{id}")
    public ResponseResult recordGet(@PathVariable("id") Long id) {
        LambdaQueryWrapper<Records> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Records::getId, id);
        return ResponseResult.success(recordsService.getOne(wrapper));
    }

    @PutMapping("/assignment")
    @ApiOperation("商机分配")
    public ResponseResult assignment(@RequestBody BusinessDto businessDto) {
        return businessService.assignment(businessDto);
    }

    @PutMapping("/back/{id}/{reason}")
    @ApiOperation("踢回公海")
    public ResponseResult back(@PathVariable("id") Long id, @PathVariable("reason") String reason) {
        Business business = new Business();
        business.setId(id);
        business.setStatus(BusinessStatusConstant.OPEN_OCEAN_POOLS);
        business.setReasons(reason);
        businessService.updateById(business);
        return ResponseResult.success();
    }

    @GetMapping("/pool")
    public PageResult<BusinessVo> pool(@ApiParam("分页参数") Integer pageNum,
                                       @ApiParam("分页参数") Integer pageSize,
                                       BusinessDto businessDto) {
        Object beginCreateTime = businessDto.getParams().get("beginCreateTime");
        Object endCreateTime = businessDto.getParams().get("endCreateTime");

        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(businessDto.getId()), Business::getId, businessDto.getId());
        wrapper.like(ObjectUtil.isNotEmpty(businessDto.getPhone()), Business::getPhone, businessDto.getPhone());
        wrapper.between(ObjectUtil.isNotEmpty(businessDto.getCreateTime()), Business::getCreateTime, beginCreateTime, endCreateTime);

        wrapper.eq(ObjectUtil.isNotEmpty(businessDto.getName()), Business::getName, businessDto.getName());
        wrapper.eq(ObjectUtil.isNotEmpty(businessDto.getSubject()), Business::getSubject, businessDto.getSubject());
        wrapper.eq(Business::getStatus, BusinessStatusConstant.OPEN_OCEAN_POOLS);
        Page<Business> page = businessService.page(new Page<>(pageNum, pageSize), wrapper);
        return PageResult.success(page, BusinessVo.class);

    }

    @PutMapping("/gain")
    public ResponseResult gain(@RequestBody AssignmentDto assignmentDto) {
        Integer[] ids = assignmentDto.getIds();
        List<Business> businesses = businessService.listByIds(Arrays.asList(ids));
        businesses.stream().forEach(business -> {
            business.setStatus(BusinessStatusConstant.NOT_FOLLOWED_UP);
            business.setOwner(UserContext.getUser());
            business.setOwnerTime(LocalDateTime.now());
            businessService.updateById(business);
        });
        return ResponseResult.success(businessService.updateBatchById(businesses));

    }
}